var assert = require('../assert');
var crypto = require('crypto');
var pingpp = require('pingpp');
var userId = 'oMrHeLd3BI';
var wx_app_id = 'wx966722d472a4146d';
var wx_app_secret = '5f09e4cddceeeee637ef7d4fde68832a';

exports.detail = function(req,res,next){
    var userId = assert.getUserId(req);
    var orderId = req.params.orderId;
    if(!userId){
        res.render('error', assert.getRes(103, "获取用户信息失败", {}, true));
        return;
    }
    if(!orderId){
        res.render('error', assert.getRes(102, "获取订单信息失败", {}, true));
        return;
    }

    var JADE_VAR = assert.getJADEVAR();
    assert.apiParseRequest('get', '/kdOrders/' + orderId, {}).then(function (result) {
            if (result) {
                JADE_VAR.orderInfo = result;
                if (typeof(result['expressCom']) != "undefined") {
                    expressScan(result['expressCom'], result['expressNO']).then(function (result) {
                        JADE_VAR.expInfo = result;
                        res.render('order/order', JADE_VAR);
                    });
                } else {
                    JADE_VAR.expInfo = {'Traces': []};
                    res.render('order/order',JADE_VAR);
                }
            } else {
                res.render('error', assert.getRes(102, "获取订单失败", {}, true));
            }
        }, function (err, error) {
            res.render('error',assert.getRes(404,"服务器错误",{},true));
        });


};

exports.orders = function(req,res,next){
    var userId = assert.getUserId(req);
    if (!userId) {
        res.render('error', assert.getRes(103, "用户获取失败", {}, true));
        return;
    }
    var JADE_VAR = assert.getJADEVAR();
        assert.apiParseRequest('get', '/kdOrders?userId=' + userId).then(function (results) {
        JADE_VAR.orderList = results;
        res.render('order/orders',JADE_VAR);
    },function(err){
        res.render('error', assert.getRes(304, "服务器失败", {}, true));
    })
};

exports.deleteOrder = function(req,res){
    var userId = assert.getUserId(req);
    if (!userId) {
        res.send(assert.getRes(103, "获取用户失败"));
        return;
    }
    var orderId = req.params.orderId;
    assert.apiParseRequest('DELETE', '/orders/' + orderId).then(function (result) {
        res.send(assert.getRes(200, "删除完成"));
    }, function (error) {
        res.send(assert.getRes(400, "删除失败"));
    })
};

exports.editOrder =function (req,res) {
    var userId = assert.getUserId(req);
    if (!userId) {
        res.send(assert.getRes(103, "获取用户失败"));
        return;
    }
    var orderId = req.params.orderId;
    var orderStatus = req.body.orderStatus;
    assert.apiParseRequest('POST', '/orders/' + orderId, {orderStatus: orderStatus}).then(function (result) {
        res.send(assert.getRes(200, "确认完成"));
    }, function (error) {
        res.send(assert.getRes(400, "设置失败"));
    })
};

exports.express = function (req,res) {
    var userId = assert.getUserId(req);
    if (!userId) {
        res.render('error', assert.getRes(103, "用户获取失败", {}, true));
        return;
    }

    var expressCode = req.query.expressCode;
    var expressNO = req.query.expressNO;
    var expressName = req.query.expressName;
    expressScan(expressCode, expressNO).then(function (result) {
        var JADE_VAR = assert.getJADEVAR();
        result.Traces.reverse();
        result.expName = expressName;
        JADE_VAR.expInfo = result;
        res.render('order/express', JADE_VAR)
    })
};

function expressScan(expCode, expNo) {
    return new Promise(function (resolve, reject) {
        var key = '36bf71c9-6315-4010-90a5-b21c4be37c32';
        var params = {};
        var requestData = JSON.stringify({"ShipperCode": expCode, "LogisticCode": expNo, "OrderCode": ""});
        var md5 = crypto.createHash('md5');
        var dataSign = requestData + key;
        var md5Str = md5.update(dataSign).digest('hex');
        var baseStr = new Buffer(md5Str).toString('base64');
        params["RequestData"] = requestData;
        params["EBusinessID"] = "1262485";
        params["RequestType"] = '1002';
        params["DataType"] = "2";
        params['DataSign'] = baseStr;
        var paramsStr = qs.stringify(params);
        var options = {
            host: 'api.kdniao.cc',
            path: '/Ebusiness/EbusinessOrderHandle.aspx',
            method: 'post',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': paramsStr.length
            }
        };
        var post_req = http.request(options, function (results) {
            results.setEncoding('utf8');
            results.on('data', function (chunk) {
                var js = JSON.parse(chunk);
                resolve(js);
            });
        });
        post_req.write(paramsStr);
        post_req.end();
    });
}

exports.confirmPay = function (req, res, next) {
    //支付订单页面
    var userId = assert.getUserId(req);
    console.log(userId);
    var payChannel = req.body.payChannel;
    if (!userId) {
        res.send(assert.getRes(101, "用户获取失败"));
        return;
    }
    if (!payChannel) {
        res.send(assert.getRes(103, "获取支付渠道失败"));
        return;
    }
    //获取支付参数
    var params = req.body.params;
    if (!params) {
        res.send(assert.getRes(102, "获取订单信息失败"));
        return;
    }
    var paramsInfo = JSON.parse(new assert.base64Assert().decode(params));
    if (!paramsInfo) {
        res.send(assert.getRes(103, "解析订单信息失败"));
        return;
    }
    //开始请求函数
    var data = {
        orderId: paramsInfo.objectId,
        orderSubject: "口袋微店商品",
        payChannel: payChannel,
        amounts: paramsInfo.payPrice * 100,
        userId: userId,
        isTest:2
    };
    //口袋微店微信支付
    if (payChannel == 'wx_pub') {
        var openId = req.session.userKDOpenId;
        if (openId) {
            data.wxOpenId = openId;
            assert.apiParseRequest('POST', '/payment', data).then(function (msg) {
                if (msg) {
                    res.send(assert.getRes(200, "获取支付凭证成功", msg));
                } else {
                    res.send(assert.getRes(201, "获取支付凭证失败"));
                }
            }, function (err) {
                res.send(assert.getRes(500, "内部错误"));
            });
        } else {
            //通过用户ID获取openId
            assert.getUserOpenIdByUid(userId).then(function (results) {
                if (!results.code) {
                    //请求成功
                    data.wxOpenId = results.result;
                    //写入到session中
                    req.session.userKDOpenId = results.result;
                    assert.apiParseRequest('POST', '/payment', data).then(function (msg) {
                        if (msg) {
                            res.send(assert.getRes(200, "获取支付凭证成功", msg));
                        } else {
                            res.send(assert.getRes(201, "获取支付凭证失败"));
                        }
                    }, function (err) {
                        res.send(assert.getRes(500, "内部错误"));
                    });
                } else {
                    //未找到openId,通知前台去微信获取
                    res.send(assert.getRes(104, "微信支付获取OpenId失败"));
                }
            }, function (error) {
                //未找到openId,通知前台去微信获取
                res.send(assert.getRes(104, "请求用户OpenId失败"));
            })
        }
    } else {
        assert.apiParseRequest('POST', '/payment', data).then(function (msg) {
            if (msg) {
                res.send(assert.getRes(200, "获取支付凭证成功", msg));
            } else {
                res.send(assert.getRes(201, "获取支付凭证失败"));
            }
        }, function (err) {
            res.send(assert.getRes(500, "内部错误"));
        });
    }

};

exports.getWxPubSign = function (req, res) {
    var charge = req.body.charge;
    pingpp.wxPubOauth.getJsapiTicket(wx_app_id, wx_app_secret, function (e, response) {
        var ticket = response.ticket;
        var signature = pingpp.wxPubOauth.getSignature(JSON.parse(charge), ticket, "http://koudai.lovepinyao.com/pay/");
        if (signature) {
            res.send(assert.getRes(200, "获取成功", signature));
        } else {
            res.send(assert.getRes(101, "获取签名失败"));
        }
    });
};

exports.paymentSuccess = function (req, res) {
    var orderId = req.query.out_trade_no;
    var tradeStatus = req.query.trade_status;
    var payOrderId = req.query.trade_no;
    var testResult = req.query.result;
    if(testResult){
        tradeStatus = true;
    }
    var userId = req.query.userId;
    req.session.userId = userId;

    if (!orderId || !tradeStatus) {
        res.render('error', assert.getRes(101, "支付失败", {}, true));
        return;
    }
    //修改状态
    assert.apiParseRequest('PUT', '/setPayInfo/' + orderId, {
        payment: 'alipay',
        payOrderId: payOrderId
    }).then(function (resultsJSON) {
        res.redirect('/orders?userId=' + userId);
    }, function (error) {
        res.render(500, "修改支付状态失败", {}, true);
    })
};

exports.setPayInfoWx = function (req, res) {
    var orderInfo = req.body.payInfo;
    var openId = req.body.openId;
    if (!orderInfo || !openId) {
        res.send('error', assert.getRes(101, "获取信息失败"));
        return;
    }
    var orderInfoOBj = JSON.parse(new assert.base64Assert().decode(orderInfo));
    var orderId = orderInfoOBj.objectId;
    if (orderId) {
        assert.apiParseRequest('PUT', '/setPayInfo/' + orderId, {
            payment: 'wx',
            payOrderId: '',
            payOpenId: openId
        }).then(function (resultsJSON) {
            res.send(assert.getRes(200, "操作成功"));
        }, function (error) {
            res.send(assert.getRes(500, "修改支付状态失败"));
        })
    } else {
        res.send('error', assert.getRes(101, "获取订单ID信息失败"));
    }
};

exports.waitPayReturn = function (req, res,next) {
    res.render('pay/payReturn',assert.getJADEVAR());
};

exports.getOrderStatus = function (req,res,next) {
    var params = req.query.params;
    if(!params){
        res.send('error', assert.getRes(101, "访问非法"));
        return;
    }
    var orderInfo = JSON.parse(new assert.base64Assert().decode(params));
    if(!orderInfo){
        res.send('error', assert.getRes(101, "数据有误"));
        return;
    }
    //查询订单支付情况
    assert.apiParseRequest('GET','/order/orderStatus?orderId='+orderInfo.orderId).then(function (results) {
        if(parseInt(results) == 1){
            res.send(assert.getRes(200, "支付成功"));
        }else{
            res.send(assert.getRes(201, "支付成功"));
        }
    })
};